﻿using System.Security.Cryptography.X509Certificates;

namespace DoNet.ApiHttpClient.Certificate
{
    //public class FileCertificateLoader : ICertificateLoader
    //{
    //    /// <summary>
    //    /// 获取证书
    //    /// </summary>
    //    /// <param name="name">证书名称（默认为商户号）</param>
    //    /// <param name="password">证书密码（默认为商户号）</param>
    //    /// <param name="type">证书平台，如微信支付等</param>
    //    /// <param name="fileName">证书文件名，默认为微信支付接口证书文件名称</param>
    //    /// <returns></returns>
    //    public X509Certificate2 LoadCertificate(string name, string password = "", string type = "WechatMch", string fileName = "apiclient_cert.p12")
    //    {
    //        if (string.IsNullOrWhiteSpace(password))
    //        {
    //            password = name;
    //        }
    //        var certPath = Path.Combine("Certs", $"{type}/{name}/{fileName}");
    //        return new X509Certificate2(certPath, password);
    //    }
    //}

    public class FileCertificateLoader : ICertificateLoader
    {
        /// <summary>
        /// 加载证书
        /// </summary>
        /// <param name="basePath">证书文件目录</param>
        /// <param name="certId">证书对应的主体，如微信商户号</param>
        /// <param name="certId">证书名称</param>
        /// <param name="fileExt">证书后缀名，p12、pfx；pem、crt、cer；der</param>
        /// <returns></returns>
        /// <exception cref="FileNotFoundException"></exception>
        public X509Certificate2 LoadCertificate(string basePath, string certId, string certName = "apiclient_cert", string fileExt = "p12")
        {
            var certPath = Path.Combine(basePath, certId, certName + "." + fileExt);
            if (File.Exists(certPath))
            {
                return fileExt switch
                {
                    "pem" or "crt" or "cer" =>
                        X509Certificate2.CreateFromPem(File.ReadAllText(certPath)),
                    "pfx" or "p12" =>
                        new X509Certificate2(File.ReadAllBytes(certPath), certId, X509KeyStorageFlags.Exportable),
                    "der" =>
                        new X509Certificate2(File.ReadAllBytes(certPath)),
                    _ => throw new NotSupportedException($"Unsupported certificate format: {fileExt}")
                };
            }
            else
                throw new FileNotFoundException($"Certificate file not found: {certPath}");
        }
    }
}
